<template>
  <div v-if="editOpen">
    <t-table :size="tableSize" :selected-row-keys="selectedRowKeys"
             @select-change="(val)=>{selectedRowKeys=val}" rowKey="id" :data="data"
             :columns="columns">
      <template #sort="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
      <template #opinion="{ row }">
        <t-input style="display: inline-block" clearable @change="() => { if (row.opinion !== '') { row.opinionStatus = 'default' } }"
                 :status="row.opinionStatus"
                 v-model="row.opinion">
          <div slot="tips" v-if="row.opinionStatus==='error'">不能为空</div>
        </t-input>
      </template>
      <template #putForward="{ row }">
        <t-input style="display: inline-block" clearable @change="() => { if (row.putForward !== '') { row.putForwardStatus = 'default' } }"
                 :status="row.putForwardStatus"
                 v-model="row.putForward">
          <div slot="tips" v-if="row.putForwardStatus==='error'">不能为空</div>
        </t-input>
      </template>
      <template #handle="{ row }">
        <t-input style="display: inline-block" clearable @change="() => { if (row.handle !== '') { row.handleStatus = 'default' } }"
                 :status="row.handleStatus"
                 v-model="row.handle">
          <div slot="tips" v-if="row.handleStatus==='error'">不能为空</div>
        </t-input>
      </template>
      <template #files="{ row }">
        <file-upload v-model="row.sysAttMainVo.sysAttMainIds" :moduleKey="row.moduleKey" :fileList="row.sysAttMainEntities" :multiple="true">
          <t-button variant="outline">
            <t-icon name="cloud-upload" slot="icon"/>
            点击上传
          </t-button>
        </file-upload>
      </template>
      <template #empty>
        <span>暂无数据 请点击新增按钮</span>
      </template>
    </t-table>
    <div style="margin-top: 10px" class="btn-group-inline">
      <t-button @click="addData">新增</t-button>
      <t-button @click="upData">上移</t-button>
      <t-button @click="downData">下移</t-button>
      <t-button @click="delData">删除</t-button>
    </div>
  </div>
  <div v-else>
    <t-table  rowKey="id" :data="data"
              :columns="columns2">
      <template #files="{ row }">
        <t-link theme="primary" hover="color" :href="file.fullFilePath" target="_blank" v-for="file in row.sysAttMainEntities" :key="file.id">{{ file.name }}</t-link>
      </template>
      <template #sort="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
    </t-table>
  </div>
</template>

<script>
import {getFiles} from "@/api/common";
import FileUpload from "@/components/FileUpload/index.vue"

export default {
  name: "opinion-fixed-list",
  components: {
    FileUpload
  },
  props: {
    value: {
      type: Array,
      default:() => [],
    },
    editOpen: {
      type: Boolean,
      default: false
    },
    tableSize: {
      type: String,
      default: 'medium'
    }
  },
  data() {
    return {
      selectedRowKeys: [],
      data: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64
        },
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'opinion',
          title: "意见或建议",
          align: "center",
        },
        {
          colKey: 'putForward',
          title: "提出单位或个人",
          align: "center",
        },
        {
          colKey: 'handle',
          title: "处理情况",
          align: "center",
        },
        {
          colKey: 'files',
          title: "附件",
          align: "center",
          width: 200
        },
      ],
      columns2: [
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'opinion',
          title: "意见或建议",
          align: "center",
        },
        {
          colKey: 'putForward',
          title: "提出单位或个人",
          align: "center",
        },
        {
          colKey: 'handle',
          title: "处理情况",
          align: "center",
        },
        {
          colKey: 'files',
          title: "附件",
          align: "center",
          width: 200
        },
      ]
    }
  },
  watch: {
    data: {
      deep: true,
      immediate: true,
      handler(val) {
        const newData = this.data.map((val, index) => ({...val, sort: index + 1}))
        this.$emit("input", newData);
      }
    },
    value: {
      deep: true,
      immediate: true,
      handler(val) {
        if(val && val.length>0){
          const newArr = val.map(data=>({
            ...data,
            initType: 'init'
          }))
          // 防止无限循环，简单比较一下
          if (JSON.stringify(val) !== JSON.stringify(this.data)) {
            this.data = newArr
            this.data.forEach(row => {
              row.moduleKey = 'YQJCLQK'
              row.sysAttMainEntities.forEach(item => {
                item.name = item.fileName
              })
            })
          }
        }
      }
    },
  },
  methods: {
    checkData() {
      const isValidate = this.data.every((val, index) => {
        if (!val.opinion) {
          this.$set(this.data[index], 'opinionStatus', 'error')
          this.$message.error(`意见及处理情况：第${index + 1}条意见或建议不能为空`);
          return false;
        }
        this.$set(this.data[index], 'opinionStatus', 'default')
        if (!val.putForward) {
          this.$set(this.data[index], 'putForwardStatus', 'error')
          this.$message.error(`意见及处理情况：第${index + 1}条提出单位或个人不能为空`);
          return false;
        }
        this.$set(this.data[index], 'putForwardStatus', 'default')
        if (!val.handle) {
          this.$set(this.data[index], 'handleStatus', 'error')
          this.$message.error(`意见及处理情况：第${index + 1}条处理情况不能为空`);
          return false;
        }
        this.$set(this.data[index], 'handleStatus', 'default')
        return true;
      });
      return isValidate;
    },
    addData() {
      const newId = Number(new Date().getTime()) + Number(Math.random() * 10)
      this.data.push({
        id: newId,
        opinion: '',
        putForward:"",
        sysAttMainVo: {
          sysAttMainIds: []
        }
      })
    },
    upData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[0].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是第一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index - 1)
      }
    },
    downData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[this.data.length - 1].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index + 1)
      }
    },
    delData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      this.data.splice(index, 1)
      this.selectedRowKeys = [];
    },
    moveInArray(arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
  }
}
</script>

<style lang="less" scoped>
/deep/ .t-table__empty{
  min-height: initial;
}
</style>
